package com.javaclimb.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javaclimb.mapper.GoodsTypeMapper;
import com.javaclimb.pojo.GoodsType;
import com.javaclimb.service.GoodsTypeService;
import com.javaclimb.util.ReturnData;
import com.javaclimb.util.ReturnDataForLayui;
import com.javaclimb.util.UpdateOrInsertResultDeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    //根据参数查询
    //开启事务（必须要支持这个事物，readOnly=true只读事物。（因为查询嘛不用增删改））
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    @Override
    public ReturnDataForLayui getList(GoodsType goodsType) {
        //把前端传递过来的第几页，一页多少个先放到分页类里面(PageHelper自带的分页类)
        PageHelper.startPage(goodsType.getPage(),goodsType.getLimit());
        //从数据库中查询到的分类
        List<GoodsType> list = goodsTypeMapper.getList(goodsType);
        //然后把list放到PageInfo（自带的分页类）
        PageInfo<GoodsType> info = new PageInfo<>(list);
        //最后返回到控制层显示到前端（data:查询到的所有值 和 count:条数）
        //然后前端通过data和count就可以显示啦
        return ReturnDataForLayui.success(list,info.getTotal());
    }

    //增加分类
    //rollbackFor事务回滚(当执行失败的时候就事务回滚)
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public ReturnData addGoodsType(GoodsType goodsType) {
        int i = goodsTypeMapper.addGoodsType(goodsType);
        return UpdateOrInsertResultDeal.dealWith(i);
    }

    //修改分类
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public ReturnData updateGoodsType(GoodsType goodsType) {
        int i = goodsTypeMapper.updateGoodsType(goodsType);
        return UpdateOrInsertResultDeal.dealWith(i);
    }

    //删除分类
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public ReturnData deleteGoodsType(GoodsType goodsType) {
        int i = goodsTypeMapper.deleteGoodsType(goodsType);
        return UpdateOrInsertResultDeal.dealWith(i);
    }

    //更新状态(后台控制是否让前台显示)
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public ReturnData updateState(GoodsType goodsType) {
        int i = goodsTypeMapper.updateState(goodsType);
        return UpdateOrInsertResultDeal.dealWith(i);
    }
}
